package com.itheima.tlias08_14.filter;

import com.alibaba.fastjson.JSONObject;
import com.itheima.tlias08_14.dto.LoginDTO;
import com.itheima.tlias08_14.mapper.EmpMapper;
import com.itheima.tlias08_14.utils.JwtUtil;
import com.itheima.tlias08_14.utils.ResultUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Objects;

@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {


    @Resource
    EmpMapper empMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("拦截器开始执行~");
//        String requestURI = request.getRequestURI();
//        if(requestURI.contains("login")){
//            return true;
//        }
        //如果不为login请求 则判断该请求中的token是否存在
        String token = request.getHeader("token");
        if (Objects.isNull(token)) {
            printErroMessage(response, "token为空，请先登入");
            return false;
        }

        //捕获解析token的异常
        try {
            JSONObject decode = JwtUtil.decode(token);
            //判断token解析出来的信息是否和目标请求中的数据吻合
            LoginDTO user = empMapper.selectByUsername(decode.getString("username"));
            if (user == null || !user.getPassword().equals(decode.getString("password"))) {
                printErroMessage(response, "token中解析密码错误");
                return false;
            }
        } catch (Exception e) {
            log.info("token过期了");
            printErroMessage(response, "token过期了");
            return false;
        }
        log.info("过滤器执行结束了");
        return true;
    }

    private static void printErroMessage(HttpServletResponse response, String message) throws IOException {
        //设置servlet输出编码utf-8
        response.setContentType("application/json;charset=utf-8");
        response.setCharacterEncoding("utf-8");

        //修改响应状态码
        //response.setStatus(401);
        //response.setStatus(HttpStatus.SC_UNAUTHORIZED);
        response.setStatus(HttpStatus.UNAUTHORIZED.value());
        //如果为空，则返回错误信息
        PrintWriter writer = response.getWriter();
        ResultUtil failure = ResultUtil.failure(message);
        //将错误信息转为json形式返回给前端
        writer.write(JSONObject.toJSONString(failure));
    }
}


